package com.daffodil.monitor.util;

import java.util.Map;

import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.daffodil.util.JacksonUtils;
import com.daffodil.util.StringUtils;

import cn.hutool.http.HttpUtil;

/**
 * -健康指标工具集
 * @author yweijian
 * @date 2022年10月20日
 * @version 2.0.0
 * @description
 */
public class HealthUtils {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String getHealth(NacosServiceInstance instance) {
        if(StringUtils.isNotNull(instance) && StringUtils.isNotEmpty(instance.getMetadata())) {
            String host = instance.getHost();
            String port = instance.getMetadata().get("management.port");
            String basePath = instance.getMetadata().get("management.endpoints.web.base-path");
            if(StringUtils.isNotEmpty(port) && StringUtils.isNotEmpty(basePath)) {
                String url = StringUtils.format("http://{}:{}{}/health", host, port, basePath);
                String response = HttpUtil.get(url);
                if(StringUtils.isNotEmpty(response)) {
                    Map result = JacksonUtils.toJavaObject(response, Map.class);
                    return JacksonUtils.getAsString(result, "status");
                }
            }
        }
        return "DOWN";
    }
}
